<?php

class ProducersController extends AppController {
	
	var $helpers = array('Html','Markdown','Javascript','Ajax','Image');

	function recommendedProducerId($name) {
		$this->set('name', $this->Producer->recommendProducerID($name));
		$this->render('recommendedProducerId','ajax');
	}
	
	function labelsForCashier($format = null) {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_ADMIN) || $this->checkLevel(AUTH_CASH)) {// must be admin or cashier
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		
		$this->layout = 'ajax';
		$addresses = $this->Producer->formatAddresses($this->Producer->findProducersWithInvoices());
		$this->set('addresses',$addresses);
		$this->set('format',$format);
	}
	
	function removeNote($note_id, $producer_id) {
		if (!$this->checkSession()) {
			$this->forceLogin();
		}
		if($this->checkLevel(AUTH_CASH)) {
			App::import('Model', 'Note');
			$note = new Note();
			$note->del($note_id);
		}
		$this->redirect('/producers/invoicing/' . $producer_id);
	}
	
	function labelsForAdmin($format = null) {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_ADMIN)) {// must be admin or cashier
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		
		if (is_null($format)) {
			$format = 'Avery 5162';
		}
		
		$this->layout = 'ajax';
		$addresses = $this->Producer->formatAddresses($this->Producer->findAll(null,null,'Member.business_name ASC'));
		$this->set('addresses',$addresses);
		$this->set('format',$format);
	}
	
	function labelsForProducer($id, $format = null) {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_ADMIN)) {
			} else if($this->checkLevel(AUTH_PROD)) {// must be producer
				if ($id != $this->userInfo['producer_id']) {
					$this->notAuth();
				}
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		
		$this->layout = 'ajax';
		App::import('Model', 'Member');
		$m = new Member();
		$addresses = $m->formatAddresses($m->getAddressesByProducer($id));
		$this->set('addresses',$addresses);
		$this->set('format',$format);
	}
	
	function add() {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_ADMIN)) {// must be admin
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		if ($this->Producer->save($this->data)) {
			$this->Producer->Member->id = $this->data['Producer']['member_id'];
			$this->Producer->Member->saveField('auth_type',AUTH_PROD);
			$this->Producer->Member->saveField('business_name',$this->data['Producer']['business_name']);
			//$this->Session->setFlash("Producer Added!",'message_ok');
			$this->redirect('/producerRequests/taken/' . $this->data['Producer']['request_id']);
		} else {
			$this->redirect("/producerRequests/respond/" . $this->data['Producer']['request_id']);
		}
	}
	
	function changeInfo($id) {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_PROD)) {// must be producer
				if ($this->checkLevel(AUTH_ADMIN)) {
					//we're OK
				} else {
					if ($id != $this->userInfo['producer_id']) {
						$this->notAuth();
					}
				}
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		//we're authorized to change this producer
		if (!empty($this->data)) {
			if ($this->Producer->save($this->data)) {
				$this->Session->setFlash("Producer Information Updated!",'message_ok');
				$redir = ($this->data['Redirect']['return']=='on') ? '/producers/changeInfo/' . $id : '/members/menu';
				$this->redirect($redir);
			}
		}
		$this->data = $this->Producer->find("producer_id = '" . $id . "'");
		//print_r($this->userInfo);
		$this->render();
	}
	
	function business_name($id = null) {
		$m = $this->Producer->getMemberInfo($id);
		return $m['Member']['business_name'];
	}
	
	function about($id) {
		$prod = $this->Producer->find('first', array('conditions' => array("Producer.producer_id" =>$id)));
		if (empty($prod)) {
			$prod = $this->Producer->find('first', array('conditions' => array("Member.username" => $id)));
		}
		if (empty($prod)) {
			$this->cakeError('error404',array(array('url'=>'/')));
		}
		$this->set("producer",$prod);
	}
	
	function products($id, $sorting = 'Category') {
		App::import('Model', 'Product');
		$p = new Product();
		$prod = $this->Producer->find("Producer.producer_id = '" . $id . "'");
		$sorts = array(
			'Name' => 'Product.product_name',
			'Category' => 'Category.category_name, Subcategory.subcategory_name',
			'Price' => 'Product.unit_price'
		);
		$this->Session->write('go_back',array('','producers','products',$id));
		$this->set('sorts',$sorts);
		$this->set('sorting',$sorting);
		$this->set('producer',$prod);
		$this->set('products',$p->c_find("Producer.producer_id = '$id'", $sorts[$sorting]));
	}
	
	function index() {
		$this->set('producers',$this->Producer->findAll("Producer.donotlist_producer = '0'",null,"Member.business_name"));
	}
	
	function view() {
		$this->redirect('/producers/index');
	}
	
	function invoicing($id,$sort = 'member', $del_id = null) {
		App::import('Model', 'BasketItem');
		$b = new BasketItem();
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_ADMIN) || $this->checkLevel(AUTH_CASH)) { //ok
			} else if($this->checkLevel(AUTH_PROD)) {// must be _this_ producer
				if ($id != $this->userInfo['producer_id']) {
					$this->notAuth();
				}
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		
		App::import('Model', 'Note');
		$note = new Note();
		if($this->checkLevel(AUTH_CASH)) {
			if(isset($this->data['Note'])) {
			// We're creating a note
				list($table_name, $table_id) = split('-', $this->data['Note']['table']);
				$this->data['Note']['table_id'] = $table_id;
				$this->data['Note']['table_name'] = $table_name;
				$note->save($this->data);
			}
		}
		
		if ($sort == 'product') {
			$sorting = array(array('product','product_name'),array('member','last_name'));
		} else if ($sort == 'member') {
			$sorting = array(array('member','last_name'),array('product','product_name'));
		}
		$prod = $this->Producer->find("Producer.producer_id = '" . $id . "'",null,null,0);
		$pName = $this->Producer->businessName($id);
		$prod['Producer']['business_name'] = $pName;
		
		if ($del_id === null) {
			$del_id = Configure::read('Delivery.delivery_id');
		}
		
		$d = new Delivery();
		$del = $d->findByDeliveryId($del_id);
		$neighbors = $d->find('neighbors', array("recursive" => -1, 'field'=>'Delivery.order_open', 'value' => $del['Delivery']['order_open']));

		
		$lines = $b->c_find("producers.producer_id = '$id'",$sort,$del_id);
		$this->set('notes', $note->getForProducer($id, $del_id));
		$this->set('producer',$prod);
		$this->set('sorting',$sorting);
		$this->set('lines',$lines);
		$this->set('del', $del);
		$this->set('neighbors', $neighbors);
		$this->pageTitle = $pName . ' Invoice';
	}
	
	function reports($page, $delivery_id = null) {
		$this->layout = 'ajax';
    if (!$this->checkSession()) {
      $this->forceLogin();
    } else {
      if($this->checkLevel(AUTH_ADMIN) || $this->checkLevel(AUTH_CASH)) { // must be administrator or cashier
      } else {
        $this->notAuth();
      }
    }
		$d = (is_null($delivery_id)) ? Configure::read('Delivery.delivery_id') : $delivery_id;
    $sort = "producer";
    if ($sort == "producer") {
			$sorting = array(array('producer','business_name'),array('member','last_name'));
			$number = 10;
    } else if ($sort == "member") {
			$sorting = array(array('member','last_name'),array('producer','business_name'));
			$number = 50;
    }
	
		$order = $sorting[0][0] . ' . ' . $sorting[0][1] . ' , ' . $sorting[1][0] . ' . ' . $sorting[1][1];
		$order = str_replace('member . last_name', 'member . last_name , member . first_name', $order);
	
		App::import('Model', 'BasketItem');
		$b = new BasketItem();
    $lines = $b->c_find(null, $sort, $d, $page, $number);
		$this->set('sorting',$sorting);
		$this->set('lines', $lines);
		$this->set('page', $page);
	}
	
	function setupForCheckIn($id) {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_ADMIN) or $this->checkLevel(AUTH_CASH) or $this->checkLevel(AUTH_PROD)) {
				if($this->userInfo['auth_type'] == AUTH_PROD) {// must be producer
					if ($id == null) {
						$id = $this->userInfo['producer_id'];
					}
					if ($id != $this->userInfo['producer_id']) {
						$this->notAuth();
					}
				}
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		App::import('Model', 'BasketItem');
		$b = new BasketItem();
		$b->breakOutDuplicates($id);
		
		$this->redirect('/producers/checkIn/' . $id);
	}
	
	function checkIn($id,$sort = 'member') {
		App::import('Model', 'BasketItem');
		$b = new BasketItem();
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_ADMIN) or $this->checkLevel(AUTH_CASH) or $this->checkLevel(AUTH_PROD)) {
				if($this->userInfo['auth_type'] == AUTH_PROD) {// must be producer
					if ($id == null) {
						$id = $this->userInfo['producer_id'];
					}
					if ($id != $this->userInfo['producer_id']) {
						$this->notAuth();
					}
				}
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		
		$this->Session->write('check-in',$id);
		
		if (!empty($this->data)) {
			if (isset($this->data['BasketItem'])) {
				foreach($this->data['BasketItem'] as $key => $value) {
					list($type, $bId, $num) = split('_',$key);
					$field = '';
					if ($type == 'q') {
						$field = 'quantity';
					} else if ($type == 'w') {
						$field = 'weight';
					}
					if ($num == 1) {
						$b->id = $bId;
						$b->saveField($field,$value);
					} else {
						$props = $b->find('BasketItem.id = "' . $bId . '"');
						$props['BasketItem']['id'] = null;
						$props['BasketItem']['weight'] = $value;
						$props['BasketItem']['quantity'] = 1;
						//print_r($props);
						$b->save($props);
						unset($b);
						$b = new BasketItem();
						$b->id = $bId;
						$b->saveField('quantity',1);
					}
					unset($b);
					$b = new BasketItem();
				}
			}
			if ($this->data['Producer']['redirect']) {
				$this->redirect('/producers/invoicing/' . $id);
			}
		}
		
		if ($sort == 'product') {
			$sorting = array('product','member');
		} else if ($sort == 'member') {
			$sorting = array('member','product');
		}
		$prod = $this->Producer->find("Producer.producer_id = '" . $id . "'",null,null,2);
		$pName = $this->Producer->businessName($id);
		$orders = array();
		
		$b = new BasketItem();
		$del = Configure::read('Delivery.delivery_id');
		$lines = $b->c_find("producers.producer_id = '$id'",$sort,$del);
		$this->set('producer',$prod);
		$this->set('sorting',$sorting);
		$this->set('lines',$lines);
	}
	
	function test() {
		//nothing going on here.  Just a sample function for test view code.
	}
	
}

?>
